package zapx

import (
	"gitee.com/guolianyu/kit/skit/third_party/config"
	kZap "github.com/go-kratos/kratos/contrib/log/zap/v2"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"os/signal"
	"strings"
	"syscall"
)

func NewZapLoggerWithConfig(cfg *config.ZapLog, level zapcore.Level) *kZap.Logger {
	var cores []zapcore.Core

	//默认是生产环境的日志配置
	encoderCfg := zap.NewProductionEncoderConfig()
	atomicLevel := zap.NewAtomicLevelAt(level)
	if atomicLevel.Level() == zap.DebugLevel {
		encoderCfg = zap.NewDevelopmentEncoderConfig()
	}

	encoder := zapcore.NewJSONEncoder(encoderCfg)
	if cfg != nil {
		if strings.ToLower(cfg.GetFormatter()) == "text" {
			encoder = zapcore.NewConsoleEncoder(encoderCfg)
		}
	}
	cores = append(cores, zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(
		zapcore.AddSync(os.Stdout),
	), atomicLevel))

	core := zapcore.NewTee(cores...)
	zlogger := zap.New(core).WithOptions()
	zapLoggerSync(zlogger)

	logger := kZap.NewLogger(zlogger)
	return logger
}

func zapLoggerSync(logger *zap.Logger) {
	c1 := make(chan os.Signal, 1)
	signal.Notify(c1, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT)
	go func(logger *zap.Logger) {
		<-c1
		_ = logger.Sync()
	}(logger)

}
